package py.com.fms.fms.session.maintenances;

//External classes imports 
//Java Classes
import java.util.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

//Seam Classes
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
import org.jboss.seam.faces.FacesMessages;
import org.jboss.seam.international.StatusMessage.Severity;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

//project classes imports
import py.com.fms.fms.bean.BranchBean;
import py.com.fms.fms.bean.EnterpriseBean;
import py.com.fms.fms.bean.PersonBean;
import py.com.fms.fms.bean.UsersBean;
import py.com.fms.fms.persistence.services.BranchServices;
import py.com.fms.fms.persistence.services.EnterpriseServices;
import py.com.fms.fms.persistence.services.PersonServices;
import py.com.fms.fms.persistence.services.UsersServices;
import py.com.fms.exception.CommonException;
import py.com.fms.session.ParamHolder;
import py.com.fms.session.ServiceSqlMap;
import py.com.fms.session.WithinHolder;
import py.com.fms.utilities.*;

@SuppressWarnings("unused")
@Name("editBranch")
@Scope(ScopeType.SESSION)
public class EditBranch {
	
	private FacesMessages facesMessages;
	@Logger
	private Log log;
	@In("#{serviceSqlMap}")
	private ServiceSqlMap sqlMap;
	private boolean editMode;
	private String initVar;
	private Date today = null;
	
	// Task Attendees Attributes 
	
	@In("#{withinHolder}")
	private WithinHolder aid;
	@In("#{paramHolder}")
	private ParamHolder param;
	@In("#{convertAssist}")
	private ConvertAssistant convert;
	@In Credentials credentials;
	@In Identity identity;
	private UsersBean user;
	
	private DateAssistant dateAssist;

	// Attribute used for saving and deleting
	private BranchBean branch;
	
	// Services
	private EnterpriseServices enSrv;
	private BranchServices brSrv;
	private UsersServices usSrv;
	
	// Collection of monedasBean
	private Collection<BranchBean> allBranches;

	// Attribute used for editing or updating
	private BranchBean editBranch;
	
//	Necessary Attributes;
	private EnterpriseBean entName = null;
	private EnterpriseBean entCod;
	private Long entId;

	
	
	
	/**
	 * [[[[[[[[[[[[ Methods ]]]]]]]]]]]] 
	 * [[[[[[[[[[-------------]]]]]]]]]]
	 * @throws CommonException 
	 */

	// Used to initialize information from a variable
	public void initData() throws CommonException {

		System.out.println("Initialization Flag = " + this.getInitVar());

		if ("S".equals(this.getInitVar())) {
			this.initBeans();
			this.initServices();
			this.initAssistants();
			this.initCollections();
			this.loadDataGrid();

			
			if(credentials != null){
				System.out.println("Credenciales Encontradas");
				this.getUser().setUserName(credentials.getUsername());
				System.out.println("User Name: " + this.getUser().getUserName());
				user = usSrv.getUserDataByName(this.getUser().getUserName());
				this.setUser(user);
				System.out.println("User: " + this.getUser());
			}else{	
				System.out.println("Credenciales Nulas");
			}
			
		}
		this.setInitVar(null);
		System.out.println("OUT");
				
	}
	public void loadParams() throws CommonException{
		this.param.initData();
		this.param.loadParams();
	}
	
	public void initBeans(){
		
		if (branch == null){
			branch = new BranchBean();
			branch.setStatus(true);
		}
		
		if (editBranch == null){
			editBranch = new BranchBean();
		}
		if (entCod == null){
			entCod = new EnterpriseBean();
		}
		
		if (entName == null){
			entName = new EnterpriseBean();
		}
		
		if (user == null){
			user = new UsersBean();
		}
		
	}
	
	public void initServices() throws CommonException{
		
		if (enSrv == null){
			enSrv = new EnterpriseServices(this.sqlMap.getConfig());
		}
		
		if (brSrv == null){
			brSrv = new BranchServices(this.sqlMap.getConfig());
		}
		
		if (usSrv == null){
			usSrv = new UsersServices(this.sqlMap.getConfig());
		}
		
				
	}
	
	public void initAssistants(){
		
		
		if(aid == null){
			aid = new WithinHolder();
		}
		
		if(param == null){
			param = new ParamHolder();
		}
		
		if(convert == null){
			convert = new ConvertAssistant();
		}
		
		if(dateAssist == null){
			dateAssist = new DateAssistant();
		}
		
	}
	
	public void initCollections(){
		if(allBranches == null){
			allBranches = new ArrayList<BranchBean>();
		}


	}
	
	public void cleanData(){

		branch = null;
		editBranch = null;
		entCod = null;
		entName = null;
		user = null;
		
		enSrv = null;
		brSrv = null;
		usSrv = null;

		aid = null;
		param = null;
		convert = null;
		dateAssist = null;

		allBranches = null;

	}

	// Used to load a grid using a collection
	private void loadDataGrid() {
		try {
			EnterpriseServices admSrv = new EnterpriseServices(this.sqlMap.getConfig());
			this.setAllBranches(brSrv.getAllBranches());
			for (BranchBean branch : this.getAllBranches()) {
				System.out.println(branch.getCod());
			}
		} catch (CommonException e) {
			e.printStackTrace();
		}
	}

	// Used to cancel
	public String cancelData() throws CommonException {
//		this.facesMessages.clear();
		this.setInitVar("S");
		this.cleanData();
		this.initData();
		return null;
	}
		

	// Used for data saving process
	public void saveNewData() throws ParseException {
		try {
//			this.facesMessages.clear();
			BranchBean newBranch = new BranchBean();
			aid = new WithinHolder();
			this.today = DateAssistant.getCurrentDate();
//			entCod = convert.getEntCod(this.getEntName());
			entId = convert.getEntId(this.getEntCod());
			
			if(this.getEntId() == null){
				System.out.println("Enterprise id is null");
			}else{
				System.out.println("Enterprise id:" + this.getEntId());
			}		

			if (this.getBranch() == null) {
				System.out.println("this.getBranch() == null");
				throw new CommonException("error.fms.menu.error.countrynotexist");
			}
			System.out.println("BEFORE SETTING VALUES");
			// Setting field values
			newBranch.setCod(convert.convertField(this.getBranch().getCod()));
			newBranch.setDescrip(convert.convertField(this.getBranch().getDescrip()));
			newBranch.setIdEnt(this.getEntId());
			newBranch.setStatus(this.getBranch().getStatus());
			newBranch.setStartDate(this.today);
			System.out.println("DATE: " + this.today);
			newBranch.setUserIns(user.getId());

			brSrv.saveNewBranch(newBranch);
			
			// Initializing field values
			newBranch = null;
			
			// Setting Initialization VAR
			this.setInitVar("S");
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO INSERTAR. " + e.getMessage());
			log.error(e);
		}finally{
			this.setBranch(null);
		}
	}
	
	// Retrieving data for updating
	public void dataToEdit(Long id) throws CommonException{
		System.out.println("id = " + id.toString());
		for (BranchBean bean : this.getAllBranches()) {
			if(bean.getId() == id){
				this.setEditBranch(bean);
				this.setEntCod(convert.getEntCod(bean.getIdEnt()));
				System.out.println("COD: " + this.getEntCod());
				return;
			}			
		}	
	}
	
	public void dataToEditUpd() throws ParseException{
		try {
			entId = convert.getEntId(this.getEntCod());
			this.getEditBranch().setIdEnt(this.getEntId());
			BranchServices admSrv = new BranchServices(this.sqlMap.getConfig());
			admSrv.updateBranch(this.getEditBranch());
		} catch (CommonException e) {
//			this.facesMessages.add(Severity.ERROR, e.getMessage());
			System.out.println("NO SE PUDO ACTUALIZAR EL REG. " + e.getMessage());
			log.error(e);
		}
	}
	
	public void dataToDelete(Long id){
		for (BranchBean bean: this.getAllBranches()){
			if (bean.getId() == id) {
				try {
					BranchServices admSrv  = new BranchServices(this.sqlMap.getConfig());
					admSrv.deleteBranchById(bean.getId());
					
				} catch (Exception e) {
//					this.facesMessages.add(Severity.ERROR, e.getMessage());
					System.out.println("NO SE BORRAR EL REGISTRO. " + e.getMessage());
					log.error(e);
				}
			}
			
		}
		this.setInitVar("S");
	}
	
	//GETTERS AND SETTERS

	public FacesMessages getFacesMessages() {
		return facesMessages;
	}

	public void setFacesMessages(FacesMessages facesMessages) {
		this.facesMessages = facesMessages;
	}

	public Log getLog() {
		return log;
	}

	public void setLog(Log log) {
		this.log = log;
	}

	public ServiceSqlMap getSqlMap() {
		return sqlMap;
	}

	public void setSqlMap(ServiceSqlMap sqlMap) {
		this.sqlMap = sqlMap;
	}

	public boolean isEditMode() {
		return editMode;
	}

	public void setEditMode(boolean editMode) {
		this.editMode = editMode;
	}

	public String getInitVar() {
		return initVar;
	}

	public void setInitVar(String initVar) {
		this.initVar = initVar;
	}

	public BranchBean getBranch() {
		return branch;
	}

	public void setBranch(BranchBean branch) {
		this.branch = branch;
	}

	public Collection<BranchBean> getAllBranches() {
		return allBranches;
	}

	public void setAllBranches(Collection<BranchBean> allBranches) {
		this.allBranches = allBranches;
	}

	public BranchBean getEditBranch() {
		return editBranch;
	}

	public void setEditBranch(BranchBean editBranch) {
		this.editBranch = editBranch;
	}

	public EnterpriseBean getEntName() {
		return entName;
	}

	public void setEntName(EnterpriseBean entName) {
		this.entName = entName;
	}

	public EnterpriseBean getEntCod() {
		return entCod;
	}

	public void setEntCod(EnterpriseBean entCod) {
		this.entCod = entCod;
	}

	public Long getEntId() {
		return entId;
	}

	public void setEntId(Long entId) {
		this.entId = entId;
	}

	public UsersBean getUser() {
		return user;
	}

	public void setUser(UsersBean user) {
		this.user = user;
	}
	
	

}
